package de.dopichaj.labrador.index;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.Validate;

/**
 * A class for managing Tag instances.
 * Handles automatic ID generation, reading and writing.
 */
public final class TagFactory {
    
    private int nextId = 0;
    private final Map<String, Tag> nameToTag = new HashMap<String, Tag>();
    private final ArrayList<Tag> idToTag = new ArrayList<Tag>();
    private PrintWriter writer = null;
    /**
     * A flag whether subsequent changes to the tag mapping are allowed.
     */
    private boolean changesAllowed = true;
    
    /**
     * Get the tag with the given name, creating it if necessary.
     */
    public Tag getTag(String name) {
        if (!nameToTag.containsKey(name)) {
            return createTag(name, nextId);
        } else {
            return nameToTag.get(name);
        }
    }
    
    /**
     * Get the tag with the given ID. This ID must be valid.
     */
    public Tag getTag(int id) {

        assert id < idToTag.size() : "Cannot get tag with unknown id " + id;
        return idToTag.get(id);
    }
    
    /**
     * Create a new tag and update the next ID.
     */
    private Tag createTag(String name, int id) {
        Validate.isTrue(changesAllowed);
        Validate.isTrue(!nameToTag.containsKey(name),
            "Trying to add existing tag " + name + "/" + id);

        Tag result = new Tag(name, nextId);
        nameToTag.put(name, result);
        
        if (id >= idToTag.size()) {
            idToTag.ensureCapacity(id + 1);
            for (int i = idToTag.size(); i <= id; i++) {
                idToTag.add(null);
            }
        }
        idToTag.set(id, result);
        if (id >= nextId) {
            nextId = id + 1;
        }
        
        if (writer != null) {
            writer.println(id + "=" + name);
        }
        
        return result;
    }
    
    /**
     * Read the tag data from the given reader.
     */
    public void read(BufferedReader reader) throws IOException {
        
        String line;
        while ((line = reader.readLine()) != null) {
            int eqpos = line.indexOf('=');
            String tag = line.substring(eqpos + 1);
            int id = Integer.parseInt(line.substring(0, eqpos));
            createTag(tag, id);
        }
    }

    /**
     * Set the PrintWriter to save new mappings to.
     * Note that only unknown tags added after this has been set to a non-null
     * value will be written.
     */
    public void setWriter(PrintWriter writer) {
        this.writer = writer;
    }
    
    /**
     * Disallow further changes to the tag mapping.
     * No new tags will be allowed after this call.
     *
     */
    public void disallowFurtherChanges() {
        changesAllowed = false;
    }
    
    public int getMaxID() {
        return nextId;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/